#include "NodeStorage.h"

NodeStorage::NodeStorage(int _capacity)
{
	this->capacity = _capacity;
	this->maps = new unsigned long[capacity / 64 + 1];
	for(int i = 0; i < capacity / 64 + 1; i++)
		this->maps[i] = 0;
	this->nodes = NGICollection(capacity);
}

bool NodeStorage::exists_in_map(int index) {
	return (maps[index / 64] & (1 << (index % 64))) != 0;
}

void NodeStorage::add(Node* n, int index) {
	maps[index / 64] |= (1 << (index % 64));
	nodes.add(n);
}

void NodeStorage::remove(Node* n, int index) {
	maps[index / 64] &= ~(1 << (index % 64));
	nodes.remove(n);
}

int NodeStorage::available_node_index() {
	for(int i = 0; i < capacity / 64; i++) {
		if(maps[i] <= 0xFFFFFFFFFFFFFFFF) {
			unsigned long l = maps[i];
			for(int k = (i == 0 ? 1 : 0); k < 64; k++) {
				if((l & (1 << k)) == 0)
					return (i * 64) + k;
			}
		}
	}

	return 0;
}

NodeStorage::~NodeStorage(void)
{
	delete[] maps;
}
